<script setup lang="ts">
import {chatProductApi} from '@/api/chat_product'
import {useBasicLayout} from '@/hooks/useBasicLayout'
import {useAppStore} from '@/store'
import {MdAdd, MdRemove} from '@vicons/ionicons4'
import {
	Cart20Filled as Cart20FilledIcon,
	GiftCardMoney20Filled as GiftCardMoney20FilledIcon
} from '@vicons/fluent'
import {chatOrderApi, SelectedProductItem, TopProductItem} from '@/api/chat_order'
import {useMessage} from 'naive-ui'
import {computed, ref} from 'vue'
// 移动端自适应相关
const {isMobile} = useBasicLayout()
const appStore = useAppStore()
const ms = useMessage()

interface Props {
	topProductShow: boolean,
	topProducts: Array<TopProductItem>
	totalAmount: number
}

interface Emit {
	(e: 'update:topProductShow', topProductShow: boolean): void

	(e: 'update:topProducts', topProducts: Array<TopProductItem>): void

	(e: 'update:totalAmount', topProducts: number): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emit>()
const topProductShow = computed({
	get: () => props.topProductShow,
	set: (topProductShow: boolean) => emit('update:topProductShow', topProductShow),
})

const topProducts = computed({
	get: () => props.topProducts,
	set: (topProducts: Array<TopProductItem>) => emit('update:topProducts', topProducts),
})

// 总金额
const totalAmount = computed({
	get: () => props.totalAmount,
	set: (totalAmount: number) => emit('update:totalAmount', totalAmount),
})

// 加入购物车
const addCart = (product: TopProductItem) => {
	if (product.selectedCount == 10) {
		ms.warning(`【${product.name}】最多只能10个`)
		return
	}
	if (product.selectedCount + 1 > product.stock) {
		ms.warning(`【${product.name}】库存不足`)
		return
	}
	topProducts.value.forEach(item => {
		if (item.id === product.id) {
			item.stock--
			item.selectedCount++
			totalAmount.value += item.price
		}
	})
}
// 移除购物车
const removeCart = (product: TopProductItem) => {
	if (product.selectedCount == 0) {
		return
	}
	topProducts.value.forEach(item => {
		if (item.id === product.id) {
			item.stock++
			item.selectedCount--
			totalAmount.value -= item.price
		}
	})
}

// 清空购物车
const clearCart = async () => {
	let needClear: boolean = false
	topProducts.value.forEach(item => {
		if (item.selectedCount > 0) {
			needClear = true
			return
		}
	})
	if (needClear) {
		try {
			const {products} = await chatProductApi.getTop4Products()
			if (products) {
				let topProductItemArr: Array<TopProductItem> = []
				products.forEach(item => {
					topProductItemArr.push({
						id: item.id,
						name: item.name,
						price: item.price,
						rewardUseTimes: item.rewardUseTimes,
						stock: item.stock,
						selectedCount: 0
					})
				})
				topProducts.value = topProductItemArr
				totalAmount.value = 0
			}
		} catch (error: any) {
			ms.error(error.message ?? 'error')
		}

	}

}

// 去下单
const orderNo = ref<string | number>('')
const userChargeModalRef = ref()
// 创建订单
const createOrder = async () => {
	let canCreate: boolean = false
	topProducts.value.forEach(item => {
		if (item.selectedCount > 0) {
			canCreate = true
			return
		}
	})
	if (!canCreate) {
		ms.warning('请先选择兑换码套餐')
		return
	}
	let selectedProductItems: Array<SelectedProductItem> = []
	topProducts.value.forEach(item => {
		if (item.selectedCount > 0) {
			selectedProductItems.push({
				productId: item.id,
				num: item.selectedCount
			})
		}
	})
	try {

		// 创建订单
		const data: string | number = await chatOrderApi.createOrder({
			selectedProductItems: selectedProductItems
		})
		ms.success('下单成功，订单号为: ' + data, {duration: 2000})
		userChargeShow.value = true
		topProductShow.value = false
		orderNo.value = data
		await nextTick(() => {
			// 调用子组件中的获取支付链接的方法
			userChargeModalRef.value.getPayUrl()
		})
	} catch (error: any) {
		ms.error(error.message ?? 'error')
	}

}
const userChargeShow = ref(false)

</script>
<template>
	<!-- 手机端	-->
	<NModal v-model:show="topProductShow" style="width: 90%;" preset="card" title="购买兑换码" v-if="isMobile">
		<NGrid :cols="1" :y-gap="16" style="width:100%;">
			<NGi v-for="item in topProducts" :key="item.id">
				<i class="item_dot" style="margin-left: 12px">超优惠</i>
				<n-space :size="24" justify="center">
					<NAlert :title="item.name"
									class="item item-primary item-ghost item-border-stroke item-text-float-up"
					>
						<template #icon>
							<NIcon>
								<GiftCardMoney20FilledIcon/>
							</NIcon>
						</template>
						<div class="item-borders">
							<div class="border-top"></div>
							<div class="border-right"></div>
							<div class="border-bottom"></div>
							<div class="border-left"></div>
						</div>
						<n-space vertical class="item-text">
							<div style="padding-top: 24px;font-weight: bolder;margin-top: 12px">
								{{ item.rewardUseTimes }}&nbsp;次 =&nbsp;¥&nbsp;{{ item.price }}&nbsp;
							</div>
							<div>
								<n-button-group style="display: flex;justify-content:space-between">
									<div style="display:flex;align-items:center;justify-content:center;font-weight: bolder">
										<span>仅剩: <span>{{ item.stock }}</span>&nbsp;张</span></div>
									<div>
										<n-badge :value="item.selectedCount" :color="appStore.theme == 'dark'?'#E88080':'#D13050'" show-zero
														 style="margin-right: 18px;margin-bottom: 2px"
										>
											<NIcon size="32">
												<Cart20FilledIcon/>
											</NIcon>
										</n-badge>
										<n-button @click="addCart(item)">
											<template #icon>
												<n-icon>
													<md-add/>
												</n-icon>
											</template>
										</n-button>
										<n-button @click="removeCart(item)">
											<template #icon>
												<n-icon>
													<md-remove/>
												</n-icon>
											</template>
										</n-button>
									</div>
								</n-button-group>
							</div>
						</n-space>
					</NAlert>
				</n-space>
			</NGi>
		</NGrid>
		<NGrid :cols="1" :y-gap="4" style="width:100%;margin-top: 16px">
			<NGi>
				<n-space :size="4" justify="center" class="flex flex-col h-full">
					<div class="p-1 flex flex-col" style="text-align: center;">
						<n-popconfirm @positive-click="createOrder">
							<template #trigger>
								<n-button type="success" dashed style="width:260px">
							<span :style="appStore.theme == 'dark'? 'color:#63E2B7;':'#18A058'"
										style="font-weight: bolder;width: 100%"
							>{{
									Math.abs(totalAmount).toFixed(2)
								}} 元</span>
								</n-button>
							</template>
							真的确认好了吗
						</n-popconfirm>
					</div>
				</n-space>
			</NGi>
			<NGi>
				<n-space :size="4" justify="center" class="flex flex-col h-full">
					<div class="p-1 flex flex-col" style="text-align: center;">
						<NButton type="error" @click="clearCart" style="width:260px">清空</NButton>
					</div>
				</n-space>
			</NGi>
		</NGrid>

		<!--		<NSpace style="margin-top: 26px;width: 240px;" x-gap="12">-->
		<!--			<n-row :gutter="12" style="justify-content: center;flex">-->
		<!--				<n-col :span="8" :push="2">-->
		<!--		-->
		<!--				</n-col>-->
		<!--				<n-col :span="8" :push="4">-->
		<!--				</n-col>-->
		<!--				<n-col :span="8" :push="1">-->

		<!--				</n-col>-->
		<!--			</n-row>-->
		<!--		</NSpace>-->

	</NModal>
	<!--PC端-->
	<NModal v-model:show="topProductShow" style="width: 90%;max-width: 900px" preset="card" title="购买兑换码" v-else>
		<NGrid :cols="2" :x-gap="12" :y-gap="16" style="width:100%;" item-responsive>
			<NGi v-for="item in topProducts" :key="item.id">
				<i class="item_dot">超优惠</i>
				<n-space :size="24" justify="center">
					<NAlert :title="item.name" style="width: 342px;height: 162px"
									class="item item-primary item-ghost item-border-stroke item-text-float-up"
					>
						<template #icon>
							<NIcon>
								<GiftCardMoney20FilledIcon/>
							</NIcon>
						</template>
						<div class="item-borders">
							<div class="border-top"></div>
							<div class="border-right"></div>
							<div class="border-bottom"></div>
							<div class="border-left"></div>
						</div>
						<n-space vertical class="item-text">
							<div style="padding-top: 24px;font-weight: bolder;margin-top: 12px">
								{{ item.rewardUseTimes }}&nbsp;次 =&nbsp;¥&nbsp;{{ item.price }}&nbsp;
							</div>
							<div>
								<n-button-group style="display: flex;justify-content:space-between">
									<div style="display:flex;align-items:center;justify-content:center;font-weight: bolder">
										<span>仅剩: <span>{{ item.stock }}</span>&nbsp;张</span></div>
									<div>
										<n-badge :value="item.selectedCount" :color="appStore.theme == 'dark'?'#E88080':'#D13050'" show-zero
														 style="margin-right: 18px;margin-bottom: 2px"
										>
											<NIcon size="32">
												<Cart20FilledIcon/>
											</NIcon>
										</n-badge>
										<n-button @click="addCart(item)">
											<template #icon>
												<n-icon>
													<md-add/>
												</n-icon>
											</template>
										</n-button>
										<n-button @click="removeCart(item)">
											<template #icon>
												<n-icon>
													<md-remove/>
												</n-icon>
											</template>
										</n-button>
									</div>
								</n-button-group>
							</div>
						</n-space>
					</NAlert>
				</n-space>
			</NGi>
		</NGrid>
		<NSpace class="product_bottom" justify="space-between" style="margin-top: 26px">
			<n-button type="success" dashed style="width: 342px;margin-left: 39px">
				<span :style="appStore.theme == 'dark'? 'color:#63E2B7;':'#18A058'" style="font-weight: bolder">{{
						Math.abs(totalAmount).toFixed(2)
					}} 元</span>
			</n-button>
			<NButton style="width: 132px;margin-left: 16px" type="error" @click="clearCart">清空</NButton>
			<n-popconfirm @positive-click="createOrder">
				<template #trigger>
					<NButton style="width: 132px;margin-right: 39px" type="primary">确认下单</NButton>
				</template>
				真的确认好了吗
			</n-popconfirm>
		</NSpace>
	</NModal>
	<UserCharge v-model:userChargeShow="userChargeShow" v-model:orderNo="orderNo" ref="userChargeModalRef"/>
</template>
<style lang="less">
.item_dot {
	position: absolute;
	z-index: 1;
	display: block;
	padding: 0 10px;
	height: 20px;
	margin-top: 48px;
	margin-left: 34px;
	background: linear-gradient(137deg, #ff5b5b 0%, #db0113 100%);
	border-radius: 0 20px 20px 0;
	color: #fff;
	text-align: center;
	font-size: 12px;
	overflow: hidden;
}

.item {
	--hue: 190;
	--ease-in-duration: 0.25s;
	--ease-in-exponential: cubic-bezier(0.95, 0.05, 0.795, 0.035);
	--ease-out-duration: 0.65s;
	--ease-out-delay: var(--ease-in-duration);
	--ease-out-exponential: cubic-bezier(0.19, 1, 0.22, 1);
	font-size: 1rem;
	color: white;
	text-decoration: none;
	background-color: hsl(var(--hue), 100%, 41%);
	border: 1px solid hsl(var(--hue), 100%, 41%);
	outline: transparent;
	overflow: hidden;
	cursor: pointer;
	user-select: none;
	white-space: nowrap;
	transition: 0.25s;

	&:hover {
		background: hsl(var(--hue), 100%, 31%);
	}

	&-primary {
		--hue: 171;
	}

	&-ghost {
		color: hsl(var(--hue), 100%, 41%);
		background-color: transparent;
		border-color: hsl(var(--hue), 100%, 41%);

		&:hover {
			color: white;
		}
	}

	&-border-stroke {
		border-color: hsla(var(--hue), 100%, 41%, 0.35);

		.item-borders {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;

			.border-top {
				position: absolute;
				top: 0;
				width: 100%;
				height: 1px;
				background: hsl(var(--hue), 100%, 41%);
				transform: scaleX(0);
				transform-origin: left;
			}

			.border-right {
				position: absolute;
				right: 0;
				width: 1px;
				height: 100%;
				background: hsl(var(--hue), 100%, 41%);
				transform: scaleY(0);
				transform-origin: bottom;
			}

			.border-bottom {
				position: absolute;
				bottom: 0;
				width: 100%;
				height: 1px;
				background: hsl(var(--hue), 100%, 41%);
				transform: scaleX(0);
				transform-origin: left;
			}

			.border-left {
				position: absolute;
				left: 0;
				width: 1px;
				height: 100%;
				background: hsl(var(--hue), 100%, 41%);
				transform: scaleY(0);
				transform-origin: bottom;
			}

			.border-left {
				transition: var(--ease-out-duration) var(--ease-out-delay) var(--ease-out-exponential);
			}

			.border-bottom {
				transition: var(--ease-out-duration) var(--ease-out-delay) var(--ease-out-exponential);
			}

			.border-right {
				transition: var(--ease-in-duration) var(--ease-in-exponential);
			}

			.border-top {
				transition: var(--ease-in-duration) var(--ease-in-exponential);
			}
		}

		&:hover {
			color: hsl(var(--hue), 100%, 41%);
			background: transparent;

			.border-top,
			.border-bottom {
				transform: scaleX(1);
			}

			.border-left,
			.border-right {
				transform: scaleY(1);
			}

			.border-left {
				transition: var(--ease-in-duration) var(--ease-in-exponential);
			}

			.border-bottom {
				transition: var(--ease-in-duration) var(--ease-in-exponential);
			}

			.border-right {
				transition: var(--ease-out-duration) var(--ease-out-delay) var(--ease-out-exponential);
			}

			.border-top {
				transition: var(--ease-out-duration) var(--ease-out-delay) var(--ease-out-exponential);
			}
		}
	}

	&-text-float-up {
		&::after {
			content: attr(data-text);
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			opacity: 0;
			transform: translateY(35%);
			transition: 0.25s ease-out;
		}

		.item-text {
			display: block;
			transition: 0.75s 0.1s var(--ease-out-exponential);
		}

		&:hover {
			.item-text {
				// 隐藏为0
				opacity: 1;
				transform: translateY(-3%);
				transition: 0.25s ease-out;
			}

			&::after {
				opacity: 1;
				transform: translateY(0);
				transition: 0.75s 0.1s var(--ease-out-exponential);
			}
		}
	}
}
</style>
